package com.hongye.why.base.listenin;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息发送者
 */
final class MessagePoster {
    private static final List<MessagePoster> posterPool = new ArrayList<>();
    Message message;
    Watcher watcher;
    MessagePoster next;

    private MessagePoster(Message message,Watcher watcher) {
        this.message = message;
        this.watcher = watcher;
    }

    static MessagePoster obtainPoster(Message message,Watcher watcher) {
        synchronized (posterPool) {
            int size = posterPool.size();
            if (size > 0) {
                MessagePoster messagePoster = posterPool.get(size - 1);
                messagePoster.message = message;
                messagePoster.watcher = watcher;
                return messagePoster;
            }
        }
        return new MessagePoster(message,watcher);
    }

    static void releaseMessagePoster(MessagePoster messagePoster) {
        messagePoster.watcher = null;
        messagePoster.message = null;
        synchronized (posterPool) {
            if (posterPool.size() < 10000) {
                posterPool.add(messagePoster);
            }
        }
    }
}
